//
//  DeviceGuanaiVc.m
//  ainkjj
//
//  Created by zhiyiLiu on 2020/3/12.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "DeviceGuanaiVc.h"
#import "Jiankang_fenxi_tianxie_vc.h"
#import "DeviceVc.h"
#import <JPUSHService.h>
#import "SKArchCutter.h"

#import "Bmi_setBabyBmi.h"
#import "Jiankang_fenxi_vc.h"

@interface DeviceGuanaiVc ()<UITextFieldDelegate, Jiankang_fenxi_delegate>
@property (weak, nonatomic) IBOutlet UILabel *bmiIndex_lb;
@property (weak, nonatomic) IBOutlet UILabel *bmi_save_time_lb;
@property (weak, nonatomic) IBOutlet UIScrollView *sv;
@property (nonatomic, copy)NSString *reg_id;
@property (nonatomic, strong)Bmi_setBabyBmi *baby_info;
@property (weak, nonatomic) IBOutlet UIButton *sg_aixiao_btn;
@property (weak, nonatomic) IBOutlet UIButton *sg_pianai_btn;
@property (weak, nonatomic) IBOutlet UIButton *sg_biaozhun_btn;
@property (weak, nonatomic) IBOutlet UIButton *sg_chaogao_btn;
@property (weak, nonatomic) IBOutlet UIButton *tz_guoqin_btn;
@property (weak, nonatomic) IBOutlet UIButton *tz_biaozhun_btn;
@property (weak, nonatomic) IBOutlet UIButton *tz_guozhong_btn;
@property (weak, nonatomic) IBOutlet UIButton *tz_feipang_btn;
@property (weak, nonatomic) IBOutlet QMUIGhostButton *qugengxin_btn;
@property (weak, nonatomic) IBOutlet UIView *view2;
@property (weak, nonatomic) IBOutlet UIView *view1;

@property(nonatomic, strong) QMUIPopupContainerView *popupByAddSubview;


@end

@implementation DeviceGuanaiVc

// 检测通知权限授权情况
- (void)checkNotificationAuthorization {
    [JPUSHService requestNotificationAuthorization:^(JPAuthorizationStatus status) {
        // run in main thread, you can custom ui
        NSLog(@"notification authorization status:%lu", status);
        [self alertNotificationAuthorization:status];
    }];
}

// 通知未授权时提示，是否进入系统设置允许通知，仅供参考
- (void)alertNotificationAuthorization:(JPAuthorizationStatus)status {
    
    if (status < JPAuthorizationStatusAuthorized) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"允许通知" message:@"只有打开通知才能收到提醒，是否进入设置允许通知？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [JPUSHService openSettingsForNotification:^(BOOL success) {
                           NSLog(@"open settings %@", success?@"success":@"failed");
                       }];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}


- (IBAction)tibei_switch_action:(UISwitch *)sender {
    
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    
    
    if (sender.isOn) {
        
        [self checkNotificationAuthorization];
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"Authorization"];
        
        
        [dict setObject:app_code forKey:@"app_code"];
        [dict setObject:[Anktool strBlankHolder:vc.deviceInfo.data.device_id] forKey:@"device_id"];
        
        [dict setObject:(int)self.tibei_tixing_wendu_tf.text.floatValue == 0 ? @(20) : self.tibei_tixing_wendu_tf.text forKey:@"threshold"];
        [dict setObject:@"2" forKey:@"type"];
        [dict setObject:self.reg_id forKey:@"reg_id"];
        [dict setObject:channel_type forKey:@"platform"];
        
        
        [PPHTTPRequest req:@"api/App/jpush" parameters:dict success:^(id response) {
            NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
            if ([error_code isEqualToString:@"0"]) {
                
                
                [sender setOn:YES];
                
                DeviceVc *vc = (DeviceVc *)self.parentViewController;
                self.tibei_tixing_wendu_tf.text = [NSString stringWithFormat:@"%ld", (long)vc.deviceInfo.data.TEM_THRESHOLD];
                
            }
            
            else
            {
                //            if ([error_code isEqualToString:@""])
                
                [sender setOn:NO];
                self.tibei_tixing_wendu_tf.text = @"";
                
                
                
                [MBProgressHUD showTipMessageInView:response[@"error_msg"]];
                
            }
        } failure:^(NSError *error) {
            [MBProgressHUD showTipMessageInView:[error localizedDescription]];
            
        }];
    }else{
        // 取消
        
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"Authorization"];
        [dict setObject:app_code forKey:@"app_code"];
        [dict setObject:[Anktool strBlankHolder:vc.deviceInfo.data.device_id] forKey:@"device_id"];
        
        [dict setObject:@"-2" forKey:@"type"];
        [dict setObject:self.reg_id forKey:@"reg_id"];
        [dict setObject:channel_type forKey:@"platform"];
        
        [PPHTTPRequest req:@"api/App/jpush" parameters:dict success:^(id response) {
            NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
            
            if ([error_code isEqualToString:@"0"]) {
                
                
                [sender setOn:NO];
                
                
//                self.tibei_tixing_wendu_tf.text = @"---";
                
            }
            
            else
            {
                //            if ([error_code isEqualToString:@""])
                
                [sender setOn:YES];
                DeviceVc *vc = (DeviceVc *)self.parentViewController;
                self.tibei_tixing_wendu_tf.text = [NSString stringWithFormat:@"%ld", (long)vc.deviceInfo.data.TEM_THRESHOLD];
                
                
                [MBProgressHUD showTipMessageInView:response[@"error_msg"]];
                
            }
        } failure:^(NSError *error) {
            [MBProgressHUD showTipMessageInView:[error localizedDescription]];
            
        }];
    }
}


- (IBAction)niaochuang_switch_action:(UISwitch *)sender {
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    
    if (sender.isOn) {
        [self checkNotificationAuthorization];

        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"Authorization"];
        
        [dict setObject:app_code forKey:@"app_code"];
        [dict setObject:[Anktool strBlankHolder:vc.deviceInfo.data.device_id] forKey:@"device_id"];
        
        [dict setObject:@"1" forKey:@"type"];
        [dict setObject:self.reg_id forKey:@"reg_id"];
        [dict setObject:channel_type forKey:@"platform"];
        
        [PPHTTPRequest req:@"api/App/jpush" parameters:dict success:^(id response) {
            NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
            if ([error_code isEqualToString:@"0"]) {
                
            }
            
            else
                //            if ([error_code isEqualToString:@""])
            {
                
                [MBProgressHUD showTipMessageInView:response[@"error_msg"]];
                
            }
        } failure:^(NSError *error) {
            [MBProgressHUD showTipMessageInView:[error localizedDescription]];
            
        }];
    }else{
        // 取消
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"Authorization"];
        [dict setObject:app_code forKey:@"app_code"];
        [dict setObject:[Anktool strBlankHolder:vc.deviceInfo.data.device_id] forKey:@"device_id"];
        
        [dict setObject:@"-1" forKey:@"type"];
        [dict setObject:self.reg_id forKey:@"reg_id"];
        [dict setObject:channel_type forKey:@"platform"];
        
        [PPHTTPRequest req:@"api/App/jpush" parameters:dict success:^(id response) {
            NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
            if ([error_code isEqualToString:@"0"]) {
                
            }
            
            else
                //            if ([error_code isEqualToString:@""])
            {
                
                [MBProgressHUD showTipMessageInView:response[@"error_msg"]];
                
            }
        } failure:^(NSError *error) {
            [MBProgressHUD showTipMessageInView:[error localizedDescription]];
            
        }];
    }
    
}
- (IBAction)jiankang_fenxi_btn_action:(QMUIGhostButton *)sender {
    Jiankang_fenxi_vc *vc= [[Jiankang_fenxi_vc alloc]init];
    vc.lastPage_bmi = self.baby_info;
    vc.hidesBottomBarWhenPushed = YES;
    DeviceVc *parvc = (DeviceVc *)self.parentViewController;
    vc.delegate = self;
    vc.deviceId = parvc.entity.device_id;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)updateWithBmiInfo:(Bmi_setBabyBmi *)info{
    self.baby_info = info;

}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [self update_guanai_ui];
    [self updateView2];

}

- (void)update_guanai_ui{
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if (vc.deviceInfo.data.TEM_THRESHOLD == 0) {
        vc.deviceInfo.data.TEM_THRESHOLD = 20;
    }
    
    if (vc.deviceInfo.data.TEM_QUILT) {
        [self.tibei_tixing_switch setOn: YES];
        
        self.tibei_tixing_wendu_tf.text = [NSString stringWithFormat:@"%ld", (long)vc.deviceInfo.data.TEM_THRESHOLD];
    }else{
        [self.tibei_tixing_switch setOn: NO];
        
//        self.tibei_tixing_wendu_tf.text = [NSString stringWithFormat:@"----"];
    }
    
    if (vc.deviceInfo.data.RT_NS) {
        [self.niaochuang_tixing_switch setOn: YES];
    }else{
        [self.niaochuang_tixing_switch setOn: NO];
    }
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.tibei_tixing_wendu_tf.delegate = self;
    
    NSString *reg = [JPUSHService registrationID];
    if (reg.length > 0) {
        self.reg_id = reg;
    }else{
        self.reg_id = @"";
    }
    
    self.view.backgroundColor = UIColor.groupTableViewBackgroundColor;
    self.jiankang_fenxi_btn.layer.borderWidth = 1;
    self.jiankang_fenxi_btn.layer.borderColor = themeColor.CGColor;
    
    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    if (vc.entity.is_virtual == NO) {
        self.tibei_tixing_wendu_tf.userInteractionEnabled = NO;
        self.tibei_tixing_switch.userInteractionEnabled = NO;
        self.niaochuang_tixing_switch.userInteractionEnabled = NO;
        self.jiankang_fenxi_btn.userInteractionEnabled = NO;
    }
    
    
    [SKArchCutter cuttingView:self.sg_aixiao_btn cuttingDirection:UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:self.sg_aixiao_btn.frame.size.height / 2 borderWidth:0 borderColor:[UIColor whiteColor] backgroundColor:[UIColor colorNamed:@"aixiaoColor"]];
    [SKArchCutter cuttingView:self.tz_guoqin_btn cuttingDirection:UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:self.tz_guoqin_btn.frame.size.height / 2 borderWidth:0 borderColor:[UIColor whiteColor] backgroundColor:[UIColor colorNamed:@"aixiaoColor"]];
    
    [SKArchCutter cuttingView:self.sg_chaogao_btn cuttingDirection:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:self.sg_chaogao_btn.frame.size.height / 2 borderWidth:0 borderColor:[UIColor whiteColor] backgroundColor:[UIColor colorNamed:@"chaogaoColor"]];
    
    [SKArchCutter cuttingView:self.tz_feipang_btn cuttingDirection:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:self.tz_feipang_btn.frame.size.height / 2 borderWidth:0 borderColor:[UIColor whiteColor] backgroundColor:[UIColor colorNamed:@"chaogaoColor"]];
    
    
    
    
    self.qugengxin_btn.ghostColor = appMainColor;

    
    
    
   
    [self req_bmi_info];

    
    
        
}
- (void)req_bmi_info{
    DeviceVc *vc = (DeviceVc *)self.parentViewController;

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
    [dict setObject:vc.entity.device_id forKey:@"deviceId"];
    
    //sender.userInteractionEnabled = NO;
    __block QMUITips *qmui_tip = [QMUITips showLoading:@"请求中..." inView:self.navigationController.view];
    
    [PPHTTPRequest req:@"java/app/bmi/getBabyBmi" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            
            self.baby_info = [Bmi_setBabyBmi mj_objectWithKeyValues:response];
            if (self.baby_info.data) {
                [self updateView2];
            }
            [qmui_tip hideAnimated:YES];
            
        }
        else{
            
            
            [qmui_tip showError:response[@"error_msg"] hideAfterDelay:2];
            
        }
        
    } failure:^(NSError *error) {
        [qmui_tip showError:[error localizedDescription] hideAfterDelay:2];
        
    }];
}
- (void)updateView2{
    self.bmiIndex_lb.text = [NSString stringWithFormat:@"%ld", (long)self.baby_info.data.bmiIndex];
    self.bmi_save_time_lb.text = self.baby_info.data.saveTime;
    
    NSArray *sg_arr = @[self.sg_aixiao_btn, self.sg_pianai_btn, self.sg_biaozhun_btn, self.sg_chaogao_btn];
    NSArray *tz_arr = @[self.tz_guoqin_btn, self.tz_biaozhun_btn, self.tz_guozhong_btn, self.tz_feipang_btn];
    if (self.baby_info.data.heightIndex - 1 > -1 && self.baby_info.data.heightIndex - 1 < sg_arr.count) {
        
        UIView *v = [self.sv viewWithTag:1111];
        if (v) {
            [v removeFromSuperview];
        }
        
        // 使用方法 1，以 addSubview: 的形式显示到界面上
        QMUIPopupContainerView *popupByAddSubview = [[QMUIPopupContainerView alloc] init];
        popupByAddSubview.tag = 1111;
        [popupByAddSubview setBackgroundColor:[UIColor colorWithRed:253.0f/255.0f green:128.0f/255.0f blue:45.0f/255.0f alpha:1.0f]];
        
        //            popupByAddSubview.imageView.image = [[UIImageMake(@"icon_emotion") qmui_imageResizedInLimitedSize:CGSizeMake(24, 24) resizingMode:QMUIImageResizingModeScaleToFill] qmui_imageWithTintColor:UIColor.qd_tintColor];
        popupByAddSubview.textLabel.text = [NSString stringWithFormat:@"%.2fcm", self.baby_info.data.height];
        popupByAddSubview.textLabel.textColor = UIColor.whiteColor;
        popupByAddSubview.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 8);
        
        popupByAddSubview.sourceView = sg_arr[self.baby_info.data.heightIndex - 1];// 相对于 button1 布局
        // 使用方法 1 时，显示浮层前需要先手动隐藏浮层，并自行添加到目标 UIView 上
//        popupByAddSubview.hidden = YES;
        [self.sv addSubview:popupByAddSubview];
        [popupByAddSubview showWithAnimated:YES];
        
    }
    if (self.baby_info.data.weightIndex - 1 > -1 && self.baby_info.data.weightIndex - 1 < tz_arr.count){
        UIView *v = [self.sv viewWithTag:2222];
        if (v) {
            [v removeFromSuperview];
        }
        // 使用方法 1，以 addSubview: 的形式显示到界面上
        QMUIPopupContainerView *popupByAddSubview = [[QMUIPopupContainerView alloc] init];
        popupByAddSubview.tag = 2222;
        popupByAddSubview.textLabel.textColor = UIColor.whiteColor;
        [popupByAddSubview setBackgroundColor:[UIColor colorWithRed:253.0f/255.0f green:128.0f/255.0f blue:45.0f/255.0f alpha:1.0f]];
        // UIColor colorWithRed:237.0f/255.0f green:177.0f/255.0f blue:72.0f/255.0f alpha:1.0f]
//        popupByAddSubview.imageView.image = [[UIImageMake(@"icon_emotion") qmui_imageResizedInLimitedSize:CGSizeMake(24, 24) resizingMode:QMUIImageResizingModeScaleToFill] qmui_imageWithTintColor:UIColor.qd_tintColor];
        popupByAddSubview.textLabel.text =  [NSString stringWithFormat:@"%.2fkg", self.baby_info.data.weight];;
        popupByAddSubview.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 8);
        
        popupByAddSubview.sourceView = tz_arr[self.baby_info.data.weightIndex - 1];// 相对于 button1 布局
        // 使用方法 1 时，显示浮层前需要先手动隐藏浮层，并自行添加到目标 UIView 上
//        popupByAddSubview.hidden = YES;
        [self.sv addSubview:popupByAddSubview];
        [popupByAddSubview showWithAnimated:YES];
    }
}
#pragma mark - ================== uitext field delegaet ==================
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    
    if (textField.text.length == 0) {
        return YES;
    }

    DeviceVc *vc = (DeviceVc *)self.parentViewController;
    
    
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"Authorization"];
    
    
    [dict setObject:app_code forKey:@"app_code"];
    [dict setObject:[Anktool strBlankHolder:vc.deviceInfo.data.device_id] forKey:@"device_id"];
    
    [dict setObject:self.tibei_tixing_wendu_tf.text forKey:@"threshold"];
    [dict setObject:@"2" forKey:@"type"];
    [dict setObject:self.reg_id forKey:@"reg_id"];
    [dict setObject:channel_type forKey:@"platform"];
    
    [PPHTTPRequest req:@"api/App/jpush" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            // 放到网络请求成功里
            vc.deviceInfo.data.TEM_THRESHOLD = self.tibei_tixing_wendu_tf.text.floatValue;

        }
        
        else
            //            if ([error_code isEqualToString:@""])
        {
            
            [MBProgressHUD showTipMessageInView:response[@"error_msg"]];
//            self.tibei_tixing_wendu_tf.text = @"";
            self.tibei_tixing_wendu_tf.text = [NSString stringWithFormat:@"%ld", (long)vc.deviceInfo.data.TEM_THRESHOLD];

        }
    } failure:^(NSError *error) {
        [MBProgressHUD showTipMessageInView:[error localizedDescription]];
//        self.tibei_tixing_wendu_tf.text = @"";
        self.tibei_tixing_wendu_tf.text = [NSString stringWithFormat:@"%ld", (long)vc.deviceInfo.data.TEM_THRESHOLD];

    }];
    
    return YES;

}

@end
